<!-- 用户分配角色 -->
<template>
  <a-modal :width="460" title="用户分配角色" :visible="visible" :confirm-loading="loading"
           @update:visible="updateVisible" @ok="save">
    <a-spin :spinning="dataLoading">
      <div style="height: 30vh" class="ele-scrollbar-hover">
        <a-tree
          :checkable="true"
          :selectable="false"
          :tree-data="roleData"
          :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
          v-model:checkedKeys="checkedKeys"
          @check="onCheck"
        />

        <!--        地域列表-->
        <div style="margin-top: 20px;" v-if="checkedKeys.includes('1339550467939639305')">
          <span>负责地域</span>
          <span style="color: red; margin-left: 4px;">*</span>
          <a-select size="large"
                    placeholder="负责地域"
                    v-model:value="region"
                    style="width: 200px;margin-left: 25px;"
                    show-search
                    allow-clear
                    :required="true">
            <a-select-option v-for="region in regionList" :key="region" :value="region">
              {{ region }}
            </a-select-option>
          </a-select>
        </div>

        <!--        代理商列表-->
        <div style="margin-top: 20px;" v-if="checkedKeys.includes('1339550467939639306')">
          <span>所属代理商</span>
          <span style="color: red; margin-left: 4px;">*</span>
          <a-select
            size="large"
            v-model:value="agentId"
            style="width: 200px;margin-left: 10px;"
            placeholder="请选择代理商"
            allowClear
          >
            <a-select-option v-for="agent in agentList" :key="agent.id" :value="agent.id">
              {{ agent.name }}
            </a-select-option>
          </a-select>
        </div>

      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { UserApi } from '@/api/UserApi';
import { onMounted, ref } from 'vue';
import { AgentApi } from '@/api/AgentApi';
import { WebUserApi } from '@/api/WebUserApi';


export default {
  name: 'UserRole',
  emits: ['update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 当前用户数据
    data: Object
  },

  setup() {
    // 加载代理商下拉数据
    const agentList = ref([]);
    const regionList = ref([]);


    async function fetchAgentList() {
      const res = await AgentApi.findList({});
      agentList.value = res.data;
    }

    async function fetchRegionList() {
      const res = await AgentApi.findRegionList({});
      regionList.value = res.data;
    }

    // 页面初次挂载时加载下拉数据
    onMounted(async () => {
      await fetchAgentList();
      await fetchRegionList();
    });

    return {
      regionList,
      agentList
    };
  },
  data() {
    return {
      // 角色数据
      roleData: [],
      // 数据请求状态
      dataLoading: false,
      // 提交状态
      loading: false,
      // 角色选中的keys
      checkedKeys: [],

      region: null,
      agentId: null
    };
  },
  watch: {
    visible() {
      if (this.visible) {
        this.query();
        this.region = null;
        this.agentId = null;
      }
    }
  },
  methods: {
    onCheck(checkedKeys, info) {
      // 清空当前已选中的所有键，准备设置新的选中项
      this.checkedKeys = [];
      // 只保留当前操作的节点
      if (info.checked) {
        this.checkedKeys.push(info.node.eventKey);
      }
      // 如果需要，这里还可以处理一些其他逻辑，比如更新UI或发送请求等
    },
    /**
     * 获取角色信息
     */
    async query() {
      this.roleData = [];
      this.checkedKeys = [];
      if (!this.data) {
        return;
      }
      this.dataLoading = true;

      // 获取系统的所有角色列表
      this.roleData = await UserApi.getRoleDropListRemake();

      // 获取用户所有的角色
      let userId = this.data.userId;
      let userRoles = await UserApi.getUserRoles({ userId });
      this.checkedKeys = userRoles.map(data => data.roleId);

      // 获取用户信息
      let userInfo = await WebUserApi.getUserInfo({ userId });
      if (userInfo.data.agentId) {
        this.agentId = userInfo.data.agentId;
      }
      if (userInfo.data.region) {
        this.region = userInfo.data.region;
      }

      // 关闭loading
      this.dataLoading = false;
    },

    /**
     * 保存角色信息
     */
    async save() {
      // 获取当前登录用户和选择的角色
      let userId = this.data.userId;
      let grantRoleIdList = this.checkedKeys;
      if (grantRoleIdList.length > 1) {
        this.$message.error('只能分配一个角色');
        return;
      }
      // 请在代理商账号界面添加经理和员工
      if (this.checkedKeys.includes('1780314166642053121') || this.checkedKeys.includes('1780314237760671746')) {
        this.$message.error('请在代理商账号界面添加经理和员工');
        return;
      }

      // 请选择地域
      if (this.checkedKeys.includes('1339550467939639305') && !this.region) {
        this.$message.error('请选择地域');
        return;
      }
      // 请选择代理商
      if (this.checkedKeys.includes('1339550467939639306') && !this.agentId) {
        this.$message.error('请选择代理商');
        return;
      }
      // 显示加载中
      this.loading = true;

      // 保存用户地域或者代理商
      if (this.agentId || this.region) {
        const selectUserId = userId;
        const agentId = this.agentId;
        const region = this.region;
        await WebUserApi.updateUserInfo({ selectUserId, agentId, region });
      }

      // 分配角色
      const result = await UserApi.grantRoles({ userId, grantRoleIdList });
      this.$message.success(result.message);

      // 移除加载中
      this.loading = false;
      this.updateVisible(false);
    }
    ,

    /**
     * 更新弹框是否隐藏，传递给父组件信息
     *
     * @author fengshuonan
     * @date 2021/4/7 16:57
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  }
}
;
</script>

<style scoped></style>
